<style>
.layui-table-cell {
	padding:1px 3px;
	height:auto;
	overflow:visible;
	text-overflow:inherit;
	white-space:normal;	           
	word-break: break-all;line-height:19px;	
}
.analytics th{padding:3px 6px;font-weight:bold;}
.bold{font-weight:bold;}
th .layui-table-cell{text-align:center;font-size:13px;line-height:19px;}
.layui-form-item .shotselect{width:120px;}
.layui-form-pane .layui-form-label{width:auto;}
.layui-layer-btn{margin-bottom: 40px;}
.layui-form-item{margin-bottom: 0px;}
.hover{color: blue}
</style>
<div class="fixed-bar">
<form class="layui-form layui-form-pane fixed-bar-form" action="{:url()}?a=factory" method="get" id="hisi-table-search-optable">
    <input type="hidden" name="export_material_type" id="export_material_type" value="null">
<div class="layui-form-item">	
	<div class="layui-inline">
		<label class="layui-form-label">订单号</label>
		<div class="layui-input-inline">
			<input type="text" name="client_ordernum" lay-verify="" placeholder="输入订单号" class="layui-input">
		</div>
	</div>
    {if env('env_site') == 'riwei' }
    <div class="layui-inline">
        <label class="layui-form-label">客户单号</label>
        <div class="layui-input-inline">
            <input type="text" name="ext_id" lay-verify="" placeholder="输入客户单号" class="layui-input">
        </div>
    </div>
    {/if}
	<div class="layui-inline">
		<label class="layui-form-label">成本审核状态</label>
		<div class="layui-input-inline">
			{:Form::select('cost_audit_status', '-1', ['-1' => '请选择', 0=>'未审核', 1=>'已审核'], '', '')}
		</div>
	</div>
	<div class="layui-inline">
		<label class="layui-form-label">订单状态</label>
		<div class="layui-input-inline">
			{:Form::select('order_status', '', ['' => '请选择', 1=>'未采购', 2=>'已采购', 3=>'已裁床', 4=>'已车缝', 5=>'已后整', 6=>'已出货', 7=>'已完成', 99=>'已废弃', 999=>'MES废除'], '', '')}
		</div>
	</div>
	<div class="layui-inline">
		<label class="layui-form-label time_input">审核日期</label>
		<div class="layui-input-inline">
			<input type="text" name="cost_audit_date_range" readonly="" id="cost_audit_date_range" lay-verify="" placeholder="选择审核日期" class="layui-input">
		</div>
	</div>
	<div class="layui-inline">
		<label class="layui-form-label time_input">下单日期</label>
		<div class="layui-input-inline">
			<input type="text" name="create_date_range" readonly="" id="create_date_range" lay-verify="" placeholder="选择下单日期" class="layui-input">
		</div>
	</div>
    <div class="layui-inline">
			<label class="layui-form-label">账号</label>
			<div class="layui-input-inline">
				{:Form::select('is_auto_import', '', $orderFrom, '', '')}
			</div>
    </div>
    <div class="layui-inline">
        <label class="layui-form-label">SKU</label>
        <div class="layui-input-inline">
            <input type="text" name="sku" lay-verify="" placeholder="输入SKU" class="layui-input">
        </div>
    </div>
    <div class="layui-inline">
		<label class="layui-form-label time_input">裁剪日期</label>
		<div class="layui-input-inline">
			<input type="text" name="caichuang_over_time" readonly="" id="caichuang_over_time" lay-verify="" placeholder="选择裁剪日期" class="layui-input">
		</div>
	</div>
    <div class="layui-inline">
        <label class="layui-form-label">所属工厂</label>
        <div class="layui-input-inline">
            {:Form::select('factory_id', '', $factoryKV, '', '')}
        </div>
    </div>
    <div class="layui-inline">
		<label class="layui-form-label">亏损状态</label>
		<div class="layui-input-inline shotselect">
			{:Form::select('exception_num', '-1', ['-1' => '请选择', 0=>'无亏损', 1=>'有亏损'], '', '')}
		</div>
	</div>
    <div class="layui-inline removeStat">
        <label class="layui-form-label">是否共用</label>
          <div class="layui-input-inline shotselect">
              {:Form::select('is_share', 2, [2 => '请选择', 0=>'不共用', 1=>'共用'], '', '')}
          </div>
    </div>
    <div class="layui-inline removeStat">
        <label class="layui-form-label">是否合裁</label>
          <div class="layui-input-inline shotselect">
              {:Form::select('is_omc', 2, [2 => '请选择', 0=>'不合裁', 1=>'合裁'], '', '')}
          </div>
    </div>
    <div class="layui-inline removeStat">
        <label class="layui-form-label">是否催单</label>
          <div class="layui-input-inline shotselect">
              {:Form::select('urge_order', 2, [2 => '请选择', 0=>'不催单', 1=>'催单'], '', '')}
          </div>
    </div>
    <div class="layui-inline">
        <label class="layui-form-label">裁剪员</label>
        <div class="layui-input-inline">
            <input type="text" name="caichuang_user_name" lay-verify="" placeholder="裁剪员关键字" style="width:130px;" class="layui-input">
        </div>
    </div>
	<div class="layui-inline">
		<button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">搜索</button>
		<button  type="button" class="layui-btn layui-btn-primary export_btn">导出</button>
	</div>
</div>
</form>
</div>
<div id="factory-stat"></div>
<table id="dataTable" lay-filter='dataTable'></table>

{include file="system@block/layui" /}

<script type="text/html" id="picTpl">
    <span class="lay-pic-container" src="{{ d.sInfo.pic }}">
		<img src="{{ d.sInfo.ori_pic }}" class="lay-pic">
		{{# if(d.status==99){ }}
			<span class="sign"><img src="/static/system/image/sign_delete.png"></span>
		{{# }else if(d.status==2){ }}
			<span class="sign"><img src="/static/system/image/sign_over.png"></span>
		{{# }else if(d.tail_status==1){ }}
			<span class="sign"><img src="/static/system/image/sign_tail.png"></span>
		{{# }else if(d.chejian_status==1){ }}
			<span class="sign"><img src="/static/system/image/sign_workshop.png"></span>
		{{# }else if(d.caichuang_status==1){ }}
			<span class="sign"><img src="/static/system/image/sign_cutting.png"></span>
		{{# }else if(d.caigou_status==1){ }}
			<span class="sign"><img src="/static/system/image/sign_purchasing_done.png"></span>
		{{# }else { }}
			<span class="sign"><img src="/static/system/image/sign_purchasing_todo.png"></span>
		{{# } }}
	</span>
</script>
<script type="text/html" id="createTimeTpl">
    {{ layui.util.toDateString(d.create_time * 1000) }} <br>
    {{ d.quantity }} 件
</script>
<script type="text/html" id="factoryTpl">
    {{ d.factory_name }} <br>
    {{ d.o_type_text }}
</script>
<script type="text/html" id="feedTpl">
    <div class="feed-btn-{{d.mid}}">
        <!--        <a href="javascript:void(0)" class="layui-btn layui-btn-primary layui-btn-xs feed-btn" data-mid="{{ d.mid }}" lay-event="feed-btn"></a>-->
        <span><a href="{:url('stallFeedDetail')}?mid={{ d.mid }}" title="采购入单 --订单号：{{d.client_ordernum}}" class="hisi-iframe feed-detail-{{ d.mid }}" hisi-data="{width: '1200px', height: '88%'}">
        [入单]{{ d.billing_caigou_count_feed }}</a></span>
    </div>
</script>
<script type="text/html" id="skuTpl">
    {{# if(d.omc_status==1){ }}
        <a class="layui-btn layui-btn-normal layui-btn-xs copy-item" id="tips{{d.client_ordernum}}" data-copy="{{d.omc_client_ordernums}}" mouseleave="close({{d.client_ordernum}})" onmouseover="showDiv({{d.client_ordernum}})">合</a><br>
    {{# } }}
    <span class="copy-item">{{ d.client_ordernum }}</span> <br>
    <span class="copy-item">{{ d.sku }}</span><br>
    {{ orderFrom[d.is_auto_import] }}<br>
	{{# if(d.client_status == 99){ }}
		<span class="red">{{ clientStatus[d.client_status] }}</span>
	{{# }else{ }}
		{{ clientStatus[d.client_status] }}
	{{# } }}
</script>
<script type="text/html" id="cuttingTpl">
    {{ d.caichuang_over_time?layui.util.toDateString(d.caichuang_over_time * 1000):'' }} <br>
	床号 {{ d.caichuang_chuanghao }} <br>
    {{ d.caichuang_user_name }}
</script>
<script type="text/html" id="shijiDosage">
    {{# if( parseFloat(d.caichuang_shiji_dosage)  > parseFloat(d.customer_dosage)){ }}  
        <span style="color:red">{{ (parseFloat(d.caichuang_shiji_dosage)).toFixed(2) }} </span>
    {{# }else{ }}
        {{ (parseFloat(d.caichuang_shiji_dosage)).toFixed(2) }} 
    {{# } }}   
</script>
<script type="text/html" id="caichuangRemarkTpl">
	{{# if((d.omList).length > 0){ }}
    {{# for(var i in d.omList[0]['omiList']){ }} 
       {{# if (d.omList[0]['omiList'][i]['caichuang_remark'] != "") { }}
            {{d.omList[0]['omiList'][i]['cloth_num_full']}} :{{d.omList[0]['omiList'][i]['caichuang_remark']}}<br>
       {{# } }} 
    {{# } }}
    {{# } }}
</script>
<script type="text/html" id="caigouSubtotalMoney">
    {{# if( layui.tool.bcdiv(d.caigou_subtotal_money, d.shicai_count) > parseFloat(d.custom_simple_cost)){ }}  
        <span style="color:red">{{ layui.tool.bcdiv(d.caigou_subtotal_money, d.shicai_count) }} </span>
    {{# }else{ }}
        {{ layui.tool.bcdiv(d.caigou_subtotal_money, d.shicai_count) }} 
    {{# } }}   
</script>
<script type="text/html" title="按钮组" id="buttonTpl">		
	{{# if(d.cost_audit_status==0){ }}
		<a href="{:url('audit')}?order_id={{ d.id }}" title="审核" class="layui-btn layui-btn-sm hisi-ajax layui-btn-warm" confirm="您确定要执行该操作吗？" refresh="false" callback="callbackAudit">审核</a>
	{{# } }}
    {{# if(d.exception_num>0){ }}
    <a href="{:url('OrderException/start_up')}?order_id={{ d.id }}" data-id="{{ d.id }}" title="启动" class="layui-btn layui-btn-sm hisi-ajax" confirm="您确定要执行该操作吗？" refresh="false" callback="callbackStart">启动</a>
    {{# } }}
</script>
<script type="text/html" title="亏损组" id="exceptionTpl">
    <span class="exception-{{ d.id }}">
	{{# if(d.exception_num>0){ }}
		<a href="{:url('OrderException/detail')}?order_id={{ d.id }}" title="亏损情况" class="blue hisi-iframe " hisi-data="{width: '90%', height: '600px'}">有亏损</a>
	{{# }else{ }}
        <a href="{:url('OrderException/detail')}?order_id={{ d.id }}" title="亏损情况" class="hisi-iframe " hisi-data="{width: '90%', height: '600px'}">无亏损</a>
    {{# } }}
    </span>
</script>
<script type="text/html" id="orderNumTpl">
	{{# for(var i in d.osList){ }}
    	{{ d.osList[i].size_name }}： {{ d.osList[i].order_count }} / {{ d.osList[i].shicai_count }} / {{ d.osList[i].jiaohuo_count }} / {{ d.osList[i].daohuo_count }} <br>
	{{# } }}
	总数：{{ d.osStat.order_count }} / {{ d.osStat.shicai_count }} / {{ d.osStat.jiaohuo_count }} / {{ d.osStat.daohuo_count }}
</script>
<script type="text/html" id="subbtnTpl">
    {{# if(d.caigou_cost_status == 1){ }}
        <a class="layui-btn layui-btn-normal layui-btn-xs subbtn-{{ d.mid }}" lay-event="save">修改</a>
    {{# }else{ }}
        <a class="layui-btn layui-btn-xs subbtn-{{ d.mid }}" lay-event="save">确认</a>
    {{# } }}
</script>
<script type="text/html" id="caigouUnitPriceTpl">
    {{# if(parseFloat(d.caigou_unitprice) > parseFloat(d.customer_price)){ }}  
        <span style="color:red">{{d.caigou_unitprice}}</span>
    {{# }else{ }}
        {{d.caigou_unitprice}}
    {{# } }}    
</script>
<script type="text/html" id="fabricWidthTpl">  
    {{# if(parseFloat(d.fabric_width-d.true_fabric_width) > 4){ }}  
    <span class="red">{{parseInt(d.true_fabric_width)}}</span> 
    {{# }else{ }}
        {{parseInt(d.true_fabric_width)}}
    {{# } }}
    /
    {{# if(parseFloat(d.true_weight-d.mInfo.weight) > 15){ }}  
        <span class="red">{{parseInt(d.true_weight)}}</span> 
    {{# }else{ }}
        {{parseInt(d.true_weight)}}
    {{# } }}
    / {{layui.tool.bcdiv(layui.tool.bcdiv(100000, d.fabric_width), d.mInfo.weight)}}
</script>
<script type="text/html" id="shijiWeightTpl">  
    {{# if(parseFloat((d.billing_caigou_kgprice-d.shiji_weight)/d.billing_caigou_kgprice) > 0.02){ }}  
    <a href="javascript:void(0);" class="hover" data-formula="实际重量-纸筒重量"><span class="red">{{d.shiji_weight}}</span></a> 
    {{# }else{ }}
        <a href="javascript:void(0);" class="hover" data-formula="实际重量-纸筒重量">{{d.shiji_weight}}</a>
    {{# } }}
</script>
<script type="text/html" id="labuLengthTpl">  
    {{# if(parseFloat((d.checkcloth_length-d.labu_lenght)/d.checkcloth_length) > 0.02 || parseFloat((d.shrink_length-d.labu_lenght)/d.shrink_length) > 0.02){ }}  
    <span class="red">{{d.labu_lenght}}</span>
    {{# }else{ }}
        {{d.labu_lenght}}
    {{# } }}
</script>
<script type="text/html" id="checkclothLengthTpl">  
    {{# if(parseFloat((d.checkcloth_length-d.checkcloth_length)/d.billing_caigou_count) > 0.03){ }}  
    <span class="red">{{d.checkcloth_length}}</span>
    {{# }else{ }}
        {{d.checkcloth_length}}
    {{# } }}
</script>
<script type="text/html" id="nameTpl">
	{{# if(d.caigou_cost_status == 0 && d.is_make_tag==1 && d.mInfo.type !="accessories"){ }}
        <a class="layui-btn layui-btn-normal layui-btn-xs layui-bg-red">催单</a>
    {{# } }}
    {{# if(d.is_share== 1){ }}
        <a class="layui-btn layui-btn-normal layui-btn-xs layui-bg-orange">共</a>
    {{# } }}
    
    {{layui.tool.formatMaterialType(d.mInfo.type,'',2)}}<span class='copy-item'>{{d.mInfo.name}}</span>
</script>
<script type="text/html" id="col3Tpl">
    {{d.fabric_width_once}} / {{d.weight_once}} /  {{d.metre_once}}
</script>
<script type="text/html" id="col3_2Tpl">
    {{# if( d.fabric_width_once != d.mInfo.fabric_width || d.weight_once != d.mInfo.weight  ){ }}
    <span style="color:red"> {{d.mInfo.fabric_width}} / {{d.mInfo.weight}} /  {{d.mInfo.metre}}</span>
    {{# }else{ }}
    {{d.mInfo.fabric_width}} / {{d.mInfo.weight}} /  {{d.mInfo.metre}}
    {{# } }}
</script>
<script type="text/html" id="col1Tpl">
    {{# if( d.col1 != d.col1_2  ){ }}
    <span style="color:red"> {{d.col1}} </span>
    {{# }else{ }}
    {{d.col1}}
    {{# } }}
</script>
<script type="text/html" id="stallOrderTimeTpl">
    <input type="text" name="stall_order_time" readonly="" id="stall_order_time{{d.mid}}" value="{{layui.util.toDateString(d.stall_order_time * 1000)}}" lay-verify="" class="layui-input stall_order_time" lay-event="stall_order_time" style="border: none">
</script>
<script type="text/html" id="caigouSubtotalMoney">

    <span class="caigouSubtotal-{{ d.mid }}">{{d.caigou_subtotal_money}}</span>
</script>
<script type="text/html" id="stallIdTpl">
    {{# if(d.stall_id!=0) { }}
    <div class="stall-select">
        {:Form::select('stall_id','', $stallsKV, 'stall-ids-{literal}{{d.mid}}{/literal}', 'layui-input','lay-search="" lay-verify="required"')}
    </div>
    {{# } }}
</script>
<script type="text/html" title="来退料明细" id="tiaoshuDetailTpl">
	{{# if(d.tiaoshu_detail!=''){ }}
		<a href="{:url('../mp/Purchasing/materialLog')}?mid={{ d.mid }}" title="来退料明细" class="hisi-iframe" hisi-data="{width: '500px', height: '400px'}">{{ d.tiaoshu_detail }}</a>
	{{# } }}
</script>
<script type="text/javascript">
    var orderFrom = {:json_encode($orderFrom);};
    var clientStatus = {:json_encode($clientStatus);};
	layui.use([ 'opTable', 'jquery', 'tool', 'laydate','layer'], function() {
		var $ = layui.jquery;
		var laydate = layui.laydate;
        var layer = layui.layer;
        $(".export_btn").click(function () {
            layer.open({
                title:'导出内容选择'
                ,btn: ['面料/里料', '辅料','全部']
                ,btnAlign: 'c'
                ,btn1: function(index, layero){
					$("#export_material_type").val("null");
                    exportData();
                    layer.close(layer.index)
                }
                ,btn2: function(index, layero){
                    $("#export_material_type").val("accessories");
                    exportData();
                }
				,btn3: function(index, layero){
                    $("#export_material_type").val("all");
                    exportData();
                }
                ,cancel: function(){
                    //右上角关闭回调
                }
            });
        });
		
        function exportData(){
            var url = $(".export_btn").parents('form').attr('action');
            var query =$(".export_btn").parents('form').serialize();
            var exportVal =$(".export_btn").attr('data-export') ? $(this).attr('data-export') : 1;
            if (url.indexOf('?') >= 0) {
                url += '&export='+exportVal+'&'+query;
            } else {
                url += '?export='+exportVal+'&'+query;
            }
            window.open(url);
            return false;
        };
		laydate.render({
		    elem: '#cost_audit_date_range'
		    ,range: '~'
		    ,theme: 'molv'
		    ,mark: {'{:$today}':''}
		    ,change: function(value, date, endDate){
		    	$('#cost_audit_date_range').val(value);
            	$('#layui-laydate1').remove();//关闭面板
            }
		});
		laydate.render({
		    elem: '#create_date_range'
		    ,range: '~'
		    ,theme: 'molv'
		    ,mark: {'{:$today}':''}
	    	,change: function(value, date, endDate){
		    	$('#create_date_range').val(value);
            	$('#layui-laydate2').remove();//关闭面板
            }
		});
		laydate.render({
		    elem: '#caichuang_over_time'
		    ,range: '~'
		    ,theme: 'molv'
		    ,mark: {'{:$today}':''}
	    	,change: function(value, date, endDate){
		    	$('#caichuang_over_time').val(value);
            	$('#layui-laydate3').remove();//关闭面板
            }
		});
        var hreStr=window.location.search,where="";
        if(hreStr.indexOf("factory") != -1){         
            where="?a=factory";
        }
		var opTable = layui.opTable.render({
			elem : '#dataTable'
			,url : '{:url()}'+where
			,page: true
			,limit: 20
            ,limits: [20,50,100,150,200]
            ,text: {
                none : '暂无相关数据'
            }
			,toolbar: '#toolbar'
	        ,defaultToolbar: ['filter', 'exports', 'print']
			,cols : [[ 
				{field:'pic',title : '图片', templet:'#picTpl',width:100}
				,{field:'client_ordernum',title : '订单号/SKU', templet:'#skuTpl',width:140}
				,{field:'create_time',title : '下单日期/订单数', templet:'#createTimeTpl'}
				,{field:'factory_id',title : '工厂/订单类型', templet:'#factoryTpl'}
				,{field:'caigou_total_money',title : '采购物料总金额'}
                ,{field:'caigou_cost_remark',title : '采购成本备注',edit:'text',style:'border-bottom:2px dotted #5FB878;'}
				,{field:'caichuang_remark',title : '裁剪备注',templet:'#caichuangRemarkTpl'}
				,{field:'caichuang_user_name',title : '裁剪日期/床号/裁剪员', templet:'#cuttingTpl'}
                ,{field:'order_num',title : '下单/裁床/车间/出货', templet:'#orderNumTpl'}
				,{field:'caigou_pricing',title : '核价情况',edit:'text',style:'border-bottom:2px dotted #5FB878;'}
                ,{field:'exception',title : '节点亏损情况',templet:'#exceptionTpl'}
				,{field:'',title : '操作',templet:'#buttonTpl'}
			]]
			,onEdit: function(obj) {
				var value = obj.value //得到修改后的值
			    ,data = obj.data //得到所在行所有键值
			    ,field = obj.field; //得到字段
			 	// 核价情况
			 	if(field == 'caigou_pricing') {	
			    	$.ajax({
				 		   type: "POST",
				 		   url: "{:url('purchasing/caigouPricing', ['_t' => 2])}",
				 		   data: "order_id="+data.id+"&remark="+value,
				 		   dataType:"json",
				 		   success: function(res){
				 			  if (res.code == 1) {
								 layer.msg(res.msg, {icon: 1});
							  } else {
								 layer.msg(res.msg, {icon: 2,anim: 6});
							  }
				 		   }
				 	});
			    }
				if(field == 'caigou_cost_remark') {	
			    	$.ajax({
				 		   type: "POST",
				 		   url: "{:url('Costing/orderCostRemark', ['_t' => 2])}",
				 		   data: "order_id="+data.id+"&cost_remark="+value,
				 		   dataType:"json",
				 		   success: function(res){
				 			  if (res.code == 1) {
								 layer.msg(res.msg, {icon: 1});
							  } else {
								 layer.msg(res.msg, {icon: 2,anim: 6});
							  }
				 		   }
				 	});
			    }
			}
			
			//  展开的列配置
			,openTable: function (itemData) {
				return {
					elem: '#child' + itemData.LAY_INDEX
					,id: 'child' + itemData.LAY_INDEX
					,data: itemData.omList
					,cellMinWidth: 100
                    ,limit: 20
					,toolbar: false
				   // ,defaultToolbar: ['filter', 'exports', 'print']
					,cols: [[
						{field: 'name', title: '材料名称',templet:'#nameTpl',width:80}
                        ,{field:'supplier',title : '指定供应商',templet:function(d){return "<a href='javascript:void(0);' class='supplier' data-supplier='"+d.mInfo.supplier+"' data-address='"+d.mInfo.address+"' data-contact='"+d.mInfo.contact+"'>"+d.mInfo.supplier+"</a>";},width:60}
						,{field:'model', title:'型号',templet:function(d){return d.mInfo.model;},width:60}
						,{field:'colornum', title:'色号',templet:function(d){return d.mInfo.colornum;},width:55}
						,{field:'color', title:'颜色',templet:function(d){return d.mInfo.color;},width:55}
                        ,{field:'col3',title : '客户幅宽/克重/米-第1次',width:70,templet:'#col3Tpl'}
                        ,{field:'col3_2',title : '客户幅宽/克重/米-第n次',width:70 ,templet:'#col3_2Tpl'}
						,{field:'col4',title : '实际幅宽/克重/米',width:70,templet:'#fabricWidthTpl'}
						,{field:'caichuang_fabric_width',title : '实裁布封',width:60}
						,{field:'billing_caigou_count_feed',title : '采购入单', templet: '#feedTpl',width:70}
                        ,{field:'material_dosage', title:'计划采购量',width:60,templet:function(d){return layui.tool.bcmul(d.material_dosage, d.quantity);}}
						,{field:'billing_caigou_count',title : '开单采购总数(米)',width:80}
						,{field:'caigou_subtotal_money',title : '采购物料单项金额',width:70}
						,{field:'col1',title : '客户物料单项金额',width:70 ,templet:'#col1Tpl'}
                        ,{field:'col1_2',title : '客户物料单项金额-计算',width:70}
						,{field:'win_money',title : '盈亏情况',width:70}
						,{field:'win_pre', title:'赢亏占比',width:60}
						,{field:'costing_remark', title:'异常备注',width:60,edit:'text',style:'border-bottom:2px dotted #5FB878;',width:70}
                        ,{field:'shiji_weight',title : '实际公斤数',templet:'#shijiWeightTpl',width:70}
						//,{field:'shiji_weight',title : '原始采购量/单价',width:76,templet:function(d){return"<span>"+d.billing_caigou_count_ori+'/'+d.caigou_unitprice+"</span>";}}
                        ,{field:'billing_caigou_kgcount',title : '开单采购总公斤数',width:70}
						,{field:'caigou_unitprice',title : '采购物料单价',width:60,templet:'#caigouUnitPriceTpl'}
                        ,{field:'customer_price',title : '客户物料单价',width:65}
                        ,{field:'unit',title : '单位',templet:function(d){return d.mInfo.unit;},width:50}
                        ,{field:'checkcloth_length',title : '验布米长',width:60,templet:'#checkclothLengthTpl'}
                        ,{field:'shrink_length',title : '缩水米长',width:60}
                        ,{field:'labu_lenght',title : '拉布米长',width:70,templet:'#labuLengthTpl'}
                        ,{field:'billing_roll_num', title:'开单总条数',width:60}
						,{field:'tiaoshu',title : '采购条数',width:60}
                        ,{field:'return_num',title : '退料匹数',width:60}
                        ,{field:'tiaoshu_detail',title : '条数明细',width:80,templet:'#tiaoshuDetailTpl'}
						,{field:'diff_meters', title:'空差',width:60,templet:function(d){return d.mInfo.diff_length;}}
                        ,{field:'tube_weight', title:'纸筒',width:60,templet:function(d){return d.mInfo.customer_weight_page;}}
                        ,{field:'rel_tube_weight', title:'实际纸筒',width:60}
                        ,{field:'fabric_price_amount',title : '面料核价金额',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:70}
                        ,{field:'dosage_price_amount',title : '用量核价金额',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:70}
                        ,{field:'caichuang_shiji_dosage',title : '实际单件用量',templet:'#shijiDosage',width:60}
                        ,{field:'customer_dosage',title : '客户单件净用量',width:65}
						,{field:'loss',title : '客户损耗%',width:60}
						,{field:'material_per',title : '料率',width:60}
						,{field:'caigou_subtotal_money',title : '实际单件物料成本',templet:'#caigouSubtotalMoney',width:70}
						,{field:'source_custom_simple_cost',title : '客户单件物料成本',width:70}						
						
                        ,{field:'yingcai_count',title : '预裁数',width:60}
						,{field:'shicai_count',title : '实裁数',width:60}
                        ,{field:'caichuang_remark',title : '裁剪备注'}
						,{field:'metre',title : '余料情况',width:60}
                        ,{field:'col6',title : '余料金额',templet:function(d){return layui.tool.bcmul(d.metre,d.caigou_unitprice);},width:60}
                        ,{field:'subbtn', title:'确认', templet:'#subbtnTpl',width:80}
					]]
                    ,done: function (res) {
                        $(".hover").hover(function(){
                            var content = $(this).attr('data-formula');
                            layer.tips(content, this,{tips:[1, '#4794ec']});
                         },function(){
                            layer.closeAll();
                         });
                        var data=res.data;
                        for (var i in data){
                            var value=layui.util.toDateString(data[i]['stall_order_time'] * 1000, 'yyyy-MM-dd');
                            var nowtime=new Date();
                            if(data[i]['stall_order_time']==0) value=nowtime.getFullYear()+"-"+(nowtime.getMonth()+1)+"-01";
                            laydate.render({
                                elem: "#stall_order_time"+data[i]['mid'], //指定元素
                                value: value
                            });
                            $('#stall-ids-'+data[i]['mid']).val(data[i]['stall_id']);
                            layui.form.render("select");
                        }
                        // 监听子表单元格修改
			            layui.table.on('edit(' + 'child' + itemData.LAY_INDEX + ')', function (obj) {
			            	var d = obj.data, field=obj.field, value = obj.value //得到修改后的值
                            console.log(d);
							var mid = d.mid;
							var custom_simple_cost=0;
							var fabricPriceAmount = d.fabric_price_amount;
							var dosagePriceAmount = d.dosage_price_amount;
							var customerPrice = d.customer_price;
							var costing_remark=d.costing_remark;
							if(field=='customer_price'){
								custom_simple_cost=d.customer_dosage * d.customer_price * (1+d.loss/100); custom_simple_cost=custom_simple_cost.toFixed(2);
								d.custom_simple_cost=custom_simple_cost;
							}
							if(!checkData(d)) return;
							$.ajax({
							   type: "POST",
							   url: "{:url('costConfirm')}",
							   data: "mid="+mid+"&fabric_price_amount="+fabricPriceAmount+"&costing_remark="+costing_remark+
							   "&dosage_price_amount="+dosagePriceAmount+"&customer_price="+customerPrice+"&custom_simple_cost="+custom_simple_cost,
							   dataType:"json",
							   success: function(res){
								  if (res.code == 1) {
									if(field=="fabric_price_amount" || field=="dosage_price_amount" || field=="customer_price"){
										var disscount_pic=parseFloat(d.fabric_price_amount)+parseFloat(d.dosage_price_amount);
										var col1_total= ((parseFloat(d.custom_simple_cost)+disscount_pic)*parseFloat(d.shicai_count)).toFixed(2); //客户物料单项金额
                                        var col1_2_total=((parseFloat(d.custom_simple_cost_2)+disscount_pic)*parseFloat(d.shicai_count)).toFixed(2);
                                        var win_money=(col1_2_total-parseFloat(d.caigou_subtotal_money)).toFixed(2);
                                        var win_pre='0.00%';
                                        win_pre=col1_2_total>0 ? (win_money/col1_2_total*100).toFixed(2) +'%' : win_pre ;
                                        obj.update({col1:col1_total,col1_2:col1_2_total,win_money:win_money,win_pre:win_pre});
										if(field=="customer_price"){
											obj.update({source_custom_simple_cost:custom_simple_cost});
											$(obj.tr.selector+ ' td[data-field="source_custom_simple_cost"]').find("div").addClass("bold");
										}
                                        $(obj.tr.selector+ ' td[data-field="col1"]').find("div").addClass("bold");
										$(obj.tr.selector+ ' td[data-field="col1_2"]').find("div").addClass("bold");
										$(obj.tr.selector+ ' td[data-field="win_money"]').find("div").addClass("bold");
										$(obj.tr.selector+ ' td[data-field="win_pre"]').find("div").addClass("bold");
									}
									 layer.msg(res.msg, {icon: 1});
									 
								  } else {
									 layer.msg(res.msg, {icon: 2,anim: 6});
								  }
							   }
							});
     	
			            });
                        // 监听子表修改按钮点击
                        layui.table.on('tool(' + 'child' + itemData.LAY_INDEX + ')', function(obj){
                            var d = obj.data;
                            var layEvent = obj.event;
                            var mid = d.mid;
                            // 点击补料
                            if (layEvent == 'feed-btn') {
                                var layerFeed = layer.prompt({title: '请输入数量', formType: 0,success:function(){
                                    // 键盘事件，判断回车
                                    $("input.layui-layer-input").on('keydown',function(e){
                                        if (e.which == 13) {
                                            feedEvent($(this).val(), mid, obj);
                                        }
                                    });
                                }}, 
                                function(number){
                                    feedEvent(number, mid, obj);
                                });
                                return ;
                            }
                            
                            // 点击确认修改
			            	if (layEvent == 'save') {
			            		var fabricPriceAmount = d.fabric_price_amount;
                                var dosagePriceAmount = d.dosage_price_amount;
                                var customerPrice = d.customer_price;
								var costing_remark=d.costing_remark;
			            		$.ajax({
			 			 		   type: "POST",
			 			 		   url: "{:url('costConfirm')}",
			 			 		   data: "mid="+mid+"&fabric_price_amount="+fabricPriceAmount+"&costing_remark="+costing_remark+"&dosage_price_amount="+dosagePriceAmount+"&customer_price="+customerPrice,
			 			 		   dataType:"json",
			 			 		   success: function(res){
			 			 			  if (res.code == 1) {
			 			 				 $('.subbtn-'+mid).addClass('layui-btn-normal');
			 			 				 $('.subbtn-'+mid).html('修改');
			 							 layer.msg(res.msg, {icon: 1});
			 						  } else {
			 							 layer.msg(res.msg, {icon: 2,anim: 6});
			 						  }
			 			 		   }
			 			 		});
			            	}
                        });
                        
                    }
		        }
            }
			,openType : 1
			,done: function(res, curr, count){
				opTable.openAll();
				var factoryStat=res.factoryStat;
                if(factoryStat.length>0){
                    var table="<table class='layui-table analytics'><thead><tr><th colspan='15'>成本赢亏报表，注：只统计面料/里料数据 <u onclick='showCostTotal()' style='cursor:pointer'>展开/关闭列表</u></th></tr><th>工厂</th><th>帐号</th><th>订单数</th><th>总订单件数</th><th>实裁数</th><th>采购总金额</th><th>客户物料金额</th><th>总赢亏情况</th><th>赢亏占比</th><th>赢利物料单数</th><th>赢利单数占比</th><th>亏损物料单数</th><th>总物料单</th><th>亏损单数占比</th><th>亏损总金额</th></thead><tbody id='cost_total_list' style='display:none'>";
					//<th>价格差异亏损总额</th><th>余料差异亏损总额</th><th>用量差异亏损总额</th><th>验布差异亏损总额</th><th>公斤差异亏损总额</th><th>克重差异亏损总额</th>
                    for(var i in factoryStat){
                        table+="<tr><td>"+factoryStat[i]['factory']
						+"</td><td>"+factoryStat[i]['default_val']
						+"</td><td>"+factoryStat[i]['order_total']
						+"</td><td>"+factoryStat[i]['order_count']
						+"</td><td>"+factoryStat[i]['shicai_count']
						+"</td><td>"+factoryStat[i]['cost_money_total']
						+"</td><td>"+factoryStat[i]['customer_cost_amount']
						+"</td><td>"+factoryStat[i]['profit_loss']
						+"</td><td>"+factoryStat[i]['win_per']
						+"</td><td>"+factoryStat[i]['win_order_num']
						+"</td><td>"+factoryStat[i]['win_order_per']
						+"</td><td>"+factoryStat[i]['lose_order_num']
						+"</td><td>"+factoryStat[i]['material_count']
						+"</td><td>"+factoryStat[i]['lose_order_per']
						+"</td><td>"+factoryStat[i]['lose_money_total']+"</td></tr>";
                    }
                    table+="</table>";
                    $("#factory-stat").html(table);
					window.showCostTotal=function(){
						var display=$("#cost_total_list").css("display")=='none' ? '' : 'none';
						$("#cost_total_list").css("display",display);
					}
                }
			}
		});
		// 单元格修改数据校验
		window.checkData = function(d) {
			var fabricPriceAmount = d.fabric_price_amount;
        	var dosagePriceAmount = d.dosage_price_amount;
			var customer_price=d.customer_price;
        	var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
        	if (!reg.test(fabricPriceAmount)) {
        		layer.msg('面料核价金额输入异常', {icon: 2,anim: 6});
        		return false;
        	}
			if (!reg.test(customer_price)) {
        		layer.msg('客户物料单价输入异常', {icon: 2,anim: 6});
        		return false;
        	}
        	if (!reg.test(dosagePriceAmount)) {
        		layer.msg('用量核价金额输入异常', {icon: 2,anim: 6});
        		return false;
        	}
        	return true;
		}
		// 审核回调
		window.callbackAudit = function(obj, res) {
			if (res.code == 1) {
				obj.remove();
			}
		}
        // 启动回调
		window.callbackStart = function(obj, res) {
			if (res.code == 1) {
                obj.remove();
                var id=$(obj).attr("data-id");
                $('.exception-'+id).text("无亏损");
			}
		}
		// 补料
		window.feedEvent = function(number, mid, obj) {
			var regInt = /^(\+|\-)?\d+$/;
			if(regInt.test(number)) {
				$.ajax({
			 		   type: "POST",
			 		   url: "{:url('PurchasingV2/costFeed')}",
			 		   data: "mid="+mid+"&number="+number,
			 		   dataType:"json",
			 		   success: function(res){
			 			  if (res.code == 1) {
			 				 var ori = $('.feed-detail-'+mid).html();
			 				 var newFeed = ori=='' ? number : (ori+(number>0?"+"+Math.abs(number):number));
			 				 $('.feed-detail-'+mid).html(newFeed);
			 				 obj.update({billing_caigou_count:res.data.billing_caigou_count,caigou_subtotal_money:res.data.caigou_subtotal_money});
			 				 $('.caigou-total-money-'+res.data.order_id).html(res.data.caigou_total_money);
							 layer.msg(res.msg, {icon: 1});
							 layer.closeAll();
						  } else {
							 layer.msg(res.msg, {icon: 2,anim: 6});
						  }
			 		   }
			 		});
			} else layer.msg('数量填写有误', {icon: 2,anim: 6});
		};
		/**
	     * layui非静态table搜索渲染
	     * @attr data-table table容器ID
	     * @attr hisi-data table基础参数
	     * @attr action 搜索请求地址
	     */
	   $(document).on('submit', '#hisiSearchOpTable,#hisi-table-search-optable', function() {
	        var that = $(this), 
	            arr = that.serializeArray(),
	            where = new Array(),
	            dataTable = that.attr('data-table') ? that.attr('data-table') : 'dataTable',
	            options = new Function('return '+ that.attr('hisi-data'))() || {page: {curr:1}};
	        
	            for(var i in arr) {
	                where[arr[i].name] = arr[i].value;
	            }
	        
	        options.url = that.attr('action');
	        options.where = where;
	        
	        opTable.reload(options);
	        return false;
	    });
        window.showDiv = function(id) {
           /* $.ajax({
                type: "POST",
                url: "{:url('omcOrdernum')}",
                data: "client_ordernum="+id,
                dataType:"json",
                success: function(res){
                    if (res.code == 1) {*/
                        tip_index_show=layer.tips($("#tips"+id).attr("data-copy"),
                        "#tips"+id+"",
                        {tips:[1, '#4794ec']});
                        $("#tips"+id+"").mouseleave(function(){
                            layer.close(tip_index_show);
                        });
            /*         }
               }
            });*/
        }

        // 刷新当前页
        window.reloadTable = function () {
            var that = $("#hisi-table-search-optable"),
                arr = that.serializeArray(),
                where = new Array(),
                dataTable = that.attr('data-table') ? that.attr('data-table') : 'dataTable',
                currPage = $(".layui-laypage-em").next().html(),
                options = new Function('return '+ that.attr('hisi-data'))() || {page: {curr:currPage}};
            for(var i in arr) {
                where[arr[i].name] = arr[i].value;
            }

            options.url = that.attr('action');
            options.where = where;

            opTable.reload(options);
            return false;
        }

      
	});
</script>